import React, { useState, useEffect,useRef,useLayoutEffect } from 'react'

function useInterval(fn,delay){
    const callbackFn =useRef(fn)
    useLayoutEffect(()=>{//dom更新后执行
        callbackFn.current=fn
    })
    useEffect(()=>{
        const timer = setInterval(() => {
            callbackFn.current()
        }, delay)
        return () => {// 组件卸载时执行
            clearInterval(timer)
        } 
    }, [delay])
}

export default function Index() {
    const [count, setCount] = useState(0)
    const updataCount=()=>{
        setCount(count+1)
    }
    useInterval(updataCount,1000)

    return (
    <div>{count}</div>
  )
}
